package ui.excute;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.SwingUtilities;

import core.engine.systemDBEngine;
import security.auth.UserManager;
import session.Session;
import storage.io.FileManager;
import storage.manager.DatabaseManager;

public class UICommandProcessor {
    private static String currentDatabase = null;
    public static final List<String> SYSTEM_COMMANDS = Arrays.asList(
        "exit", "backup", "create_db", "create_table", "insert_data",
        "reset_system", "register", "login", "logout", "users", "databases",
        "delete_db", "unuse", "add_column", "drop_column"
    );

    public static Object process(String command) {
        command = command.trim();
        if (command.isEmpty()) return "";

        // 检查系统表是否已初始化
        try {
            if (!systemDBEngine.checkSystemTablesInitialized()) {
                System.err.println("[WARN] 系统表未初始化，正在初始化...");
                systemDBEngine.initSystemTables();
            }
        } catch (Exception e) {
            return "系统初始化失败: " + e.getMessage();
        }

        // 获取命令类型
        String commandType = command.toLowerCase().split("\\s+")[0];

        // 处理系统命令
        if (SYSTEM_COMMANDS.contains(commandType)) {
            return processSystemCommand(commandType, command);
        }

        // 处理SQL命令
        return processSQLCommand(command);
    }

    public static String processSystemCommand(String commandType, String fullCommand) {
        try {
            switch (commandType) {
                case "create_db":
                    return handleCreateDatabase(fullCommand);
                case "delete_db":
                    return handleDeleteDatabase(fullCommand);
                case "register":
                    return handleUserRegistration(fullCommand);
                case "login":
                    return handleUserLogin(fullCommand);
                case "logout":
                    return handleUserLogout();
                case "users":
                    return handleShowUsers();
                case "databases":
                    return handleShowDatabases();
                case "unuse":
                    return handleUnuse();
                case "reset_system":
                    return handleResetSystem(fullCommand);
                case "backup":
                    return handleBackupCommand(fullCommand);
                default:
                    return "该系统命令暂未在UI中实现: " + commandType;
            }
        } catch (Exception e) {
            return "执行系统命令出错: " + e.getMessage();
        }
    }

    private static String handleCreateDatabase(String command) {
        Session session = Session.getCurrentSession();
        if (session == null) return "请先登录";

        String[] parts = command.split("\\s+");
        if (parts.length < 2) return "用法: create_db 数据库名";

        // 清理和验证数据库名称
        String dbName = parts[1].trim();
        if (dbName.endsWith(";")) {
            dbName = dbName.substring(0, dbName.length() - 1).trim();
        }
        if (dbName.isEmpty()) {
            return "数据库名称不能为空";
        }
        if (!dbName.matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
            return "数据库名称只能包含字母、数字和下划线，且不能以数字开头";
        }

        String username = session.getUsername();

        try {
            int result = DatabaseManager.createDatabase(dbName, username);
            if (result == 1) {
                return "数据库 [" + dbName + "] 创建成功";
            } else {
                return "数据库创建失败";
            }
        } catch (Exception e) {
            return "创建数据库出错: " + e.getMessage();
        }
    }

    private static String handleDeleteDatabase(String command) {
        Session session = Session.getCurrentSession();
        if (session == null) return "请先登录";

        String[] parts = command.split("\\s+");
        if (parts.length < 2) return "用法: delete_db 数据库名";

        // 清理和验证数据库名称
        String dbName = parts[1].trim();
        if (dbName.endsWith(";")) {
            dbName = dbName.substring(0, dbName.length() - 1).trim();
        }
        if (dbName.isEmpty()) {
            return "数据库名称不能为空";
        }
        if (!dbName.matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
            return "数据库名称只能包含字母、数字和下划线，且不能以数字开头";
        }

        try {
            int result = session.deleteDatabase(dbName);
            if (result == 1) {
                return "✅ 数据库 [" + dbName + "] 删除成功";
            } else {
                return "❌ 数据库删除失败";
            }
        } catch (Exception e) {
            return "❌ 删除数据库出错: " + e.getMessage();
        }
    }

    private static String handleUserRegistration(String command) {
        String[] parts = command.split("\\s+");
        if (parts.length < 3) return "用法: register 用户名 密码";

        String username = parts[1];
        String password = parts[2];
        int level = UserManager.NORMAL_LEVEL; // 默认普通用户

        if (UserManager.createUser(username, password, level)) {
            return "用户 [" + username + "] 注册成功";
        } else {
            return "用户注册失败";
        }
    }

    private static String handleUserLogin(String command) {
        String[] parts = command.split("\\s+");
        if (parts.length < 3) return "用法: login 用户名 密码";

        String username = parts[1];
        String password = parts[2];

        Session session = UserManager.login(username, password);
        if (session != null) {
            return "用户 [" + username + "] 登录成功";
        } else {
            return "登录失败，用户名或密码错误";
        }
    }

    private static String handleUserLogout() {
        Session session = Session.getCurrentSession();
        if (session == null) return "当前没有登录用户";

        UserManager.logout(session);
        return "用户 [" + session.getUsername() + "] 已登出";
    }

    private static String handleShowUsers() {
        Session session = Session.getCurrentSession();
        if (session == null) return "请先登录";

        // 调用UserManager.showAllUsers()并捕获输出
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        UserManager.showAllUsers(session.getUsername(), pw);
        pw.flush();
        return sw.toString();
    }

    private static String handleShowDatabases() {
        List<String> databases = getAllDatabases();
        if (databases.isEmpty()) return "没有可用的数据库";

        StringBuilder sb = new StringBuilder("数据库列表:\n");
        for (String db : databases) {
            sb.append(db).append("\n");
        }
        return sb.toString();
    }

    private static String handleUnuse() {
        Session session = Session.getCurrentSession();
        if (session == null) return "请先登录";

        session.setCurrentDatabase(null, null);
        return "已清除当前数据库选择";
    }

    private static String handleResetSystem(String command) {
        Session session = Session.getCurrentSession();
        if (session == null) return "请先登录";
        if (session.getUserLevel() != UserManager.ADMIN_LEVEL) return "需要管理员权限";

        // 检查确认参数
        String[] parts = command.split("\\s+");
        boolean confirmed = parts.length > 1 && ("y".equalsIgnoreCase(parts[1]) || "yes".equalsIgnoreCase(parts[1]));

        if (!confirmed) {
            return "⚠️ 警告: 此操作将重置整个系统，所有数据将丢失！\n" +
                   "请确认操作 (y/n): ";
        }

        try {
            // 1. 通过UserManager.logout()登出所有用户
            // (按照Main.java的实现方式，这里应该直接调用systemDBEngine.resetSystemDB()
            // 它会内部处理用户登出逻辑)

            // 2. 执行系统数据库重置
            if (systemDBEngine.resetSystemDB()) {
                return "✅ 系统已重置成功";
            } else {
                return "❌ 系统重置失败";
            }
        } catch (Exception e) {
            return "❌ 系统重置出错: " + e.getMessage();
        }
    }

    private static String handleBackupCommand(String command) {
        String[] parts = command.split("\\s+");
        if (parts.length < 3) return "用法: backup 数据库名 备份路径";

        String dbName = parts[1];
        String backupPath = parts[2];

        try {
            if (FileManager.backupDatabase(dbName, backupPath)) {
                return "数据库备份成功: " + backupPath;
            } else {
                return "数据库备份失败";
            }
        } catch (Exception e) {
            return "备份出错: " + e.getMessage();
        }
    }

    public static Object processSQLCommand(String sql) {
        Session session = Session.getCurrentSession();
        if (session == null) return "❌ 请先登录";

        try {
            Session currentSession = Session.getCurrentSession();
            String currentSessionDbName = currentSession.getCurrentDatabaseName();
            String currentSessionDbOwner = currentSession.getCurrentUser();

            String currentDbDisplay = "未选择";
            if (currentSessionDbName != null && currentSessionDbOwner != null) {
                currentDbDisplay = currentSessionDbOwner + "." + currentSessionDbName;
            } else if (currentSessionDbName != null) {
                currentDbDisplay = currentSessionDbName + " (所有者未知)";
            }

            /*
            output.append("[DEBUG] 当前会话状态 - 用户: ")
                  .append(currentSession.getUsername())
                  .append(", 数据库: ")
                  .append(currentDbDisplay)
                  .append("\n");

             */

            // 特殊处理SHOW TABLES
            if (sql.toUpperCase().startsWith("SHOW TABLES")) {
                String[] parts = sql.split("\\s+");
                String ownerForShow = null;
                String dbForShow = null;

                if (parts.length > 2 && parts[2].equalsIgnoreCase("FROM") && parts.length > 3) {
                    String ownerAndDbName = parts[3].replace(";", "").trim();
                    String[] dbIdentifierParts = ownerAndDbName.split("\\.");
                    if (dbIdentifierParts.length == 2) {
                        ownerForShow = dbIdentifierParts[0];
                        dbForShow = dbIdentifierParts[1];
                    } else {
                        return "❌ SHOW TABLES FROM 语法错误。数据库名需使用 'ownerName.dbName' 格式。";
                    }
                } else {
                    ownerForShow = currentSessionDbOwner;
                    dbForShow = currentSessionDbName;
                }

                if (dbForShow == null || ownerForShow == null) {
                    return "❌ 错误：没有选择数据库或所有者信息不完整 (SHOW TABLES)。请使用 USE 命令。";
                }

                String tables = DatabaseManager.getTablesAsString(ownerForShow, dbForShow);
                return tables;
            }

            // 处理DESCRIBE/DESC命令
            if (sql.toUpperCase().startsWith("DESCRIBE ") || sql.toUpperCase().startsWith("DESC ")) {
                String[] parts = sql.split("\\s+");
                if (parts.length > 1) {
                    String tableName = parts[1].replace(";", "").trim();
                    if (currentSessionDbName == null || currentSessionDbOwner == null) {
                        return "❌ 错误：没有选择数据库或所有者信息不完整 (DESCRIBE)。请使用 USE 命令。";
                    }
                    System.out.println("[UICommandProcessor] 执行DESCRIBE命令: 表名=" + tableName);
                    List<String[]> tableInfo = session.describeTable(tableName);
                    return tableInfo; // 直接返回表结构数据给调用者
                } else {
                    return "❌ 语法错误: 请指定表名 (DESCRIBE table_name)";
                }
            }

            // USE 命令
            if (sql.trim().toUpperCase().startsWith("USE ")) {
                int status = currentSession.executeUpdate(sql);
                if (status == 1) {
                    String usedDb = currentSession.getCurrentDatabaseName();
                    String usedOwner = currentSession.getCurrentUser();
                    refreshUIAfterDatabaseChange(); // 刷新UI
                    return "✅ 数据库已切换到: " + usedOwner + "." + usedDb;
                } else if (status == -1) {
                    return "❌ 切换数据库失败: 数据库不存在或无权限。";
                } else {
                    String[] parts = sql.split("\\s+");
                    String targetDb = "未知";
                    if (parts.length > 1) targetDb = parts[1].replace(";", "");
                    return "❌ 切换数据库失败: " + targetDb;
                }
            }

            // SELECT 查询
            boolean isQuery = sql.trim().toUpperCase().startsWith("SELECT");

            long startTime = System.currentTimeMillis();

            if (isQuery) {
                if (currentSessionDbName == null || currentSessionDbOwner == null) {
                    return "❌ 错误：没有选择数据库 (SELECT)。请使用 USE 命令。";
                }

                ArrayList<ArrayList<String>> results = currentSession.executeQuery(sql);
                return results;
            } else {
                if ((currentSessionDbName == null || currentSessionDbOwner == null) &&
                    (sql.trim().toUpperCase().startsWith("CREATE TABLE") ||
                     sql.trim().toUpperCase().startsWith("ALTER TABLE") ||
                     sql.trim().toUpperCase().startsWith("DROP TABLE") ||
                     sql.trim().toUpperCase().startsWith("INSERT"))) {
                    return "❌ 请先使用USE语句选择数据库 (DML/DDL)";
                }

                int status = currentSession.executeUpdate(sql);

                // 检查是否是表结构变更操作并刷新UI
                String upperSql = sql.trim().toUpperCase();
                if (status >= 0 && (
                    upperSql.startsWith("CREATE TABLE") ||
                    upperSql.startsWith("DROP TABLE") ||
                    upperSql.startsWith("ALTER TABLE"))) {
                    refreshUIAfterTableChange();
                }

                if (status >= 0) {
                    String commandAction = sql.trim().toUpperCase().split("\\s+")[0];
                    return "✅ " + commandAction + " 执行成功。影响行数: " + status;
                } else {
                    return "❌ 命令执行失败。错误码: " + status;
                }
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            return "❌ SQL 执行出错: " + e.getMessage();
        }
    }

    public static List<ArrayList<String>> parseShowTables(String output) {
        List<ArrayList<String>> result = new ArrayList<>();
        String[] lines = output.split("\\r?\\n");

        // 检查是否为错误信息
        if (output.startsWith("❌")) {
            ArrayList<String> errorRow = new ArrayList<>();
            errorRow.add(output);
            result.add(errorRow);
            return result;
        }

        // 从第二行开始遍历（跳过标题）
        for (int i = 1; i < lines.length; i++) {
            String line = lines[i].trim();
            if (line.equals("(无表)")) {
                break; // 没有表，直接返回空列表
            }
            if (line.startsWith("- ")) {
                String tableName = line.substring(2).trim(); // 去除 "- "
                if (!tableName.isEmpty()) {
                    ArrayList<String> row = new ArrayList<>();
                    row.add(tableName);
                    result.add(row);
                }
            }
        }

        return result;
    }

    private static String formatQueryResults(List<String[]> results) {
        if (results == null || results.isEmpty()) return "查询无结果";

        StringBuilder sb = new StringBuilder("查询结果:\n");

        // 表头
        String[] header = results.get(0);
        for (String col : header) {
            sb.append(col).append("\t");
        }
        sb.append("\n");

        // 数据行
        for (int i = 1; i < results.size(); i++) {
            String[] row = results.get(i);
            for (String cell : row) {
                sb.append(cell).append("\t");
            }
            sb.append("\n");
        }

        return sb.toString();
    }

    /**
     * 获取当前用户可访问的所有数据库
     * 包括用户自己创建的数据库和被授权访问的其他用户的数据库
     *
     * @return 数据库列表，格式为"所有者.数据库名"
     */
    public static List<String> getAllDatabases() {
        // 保存原始的标准输出流
        PrintStream originalOut = System.out;

        // 创建一个 ByteArrayOutputStream 来捕获输出内容
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        System.setOut(ps);

        try {
            // 调用 DatabaseManager.showDatabases 方法
            DatabaseManager.showDatabases(UserManager.getCurrentUser());
        } finally {
            // 恢复标准输出流
            System.setOut(originalOut);
        }

        // 将捕获的输出内容转换为字符串数组
        String output = baos.toString();
        String[] lines = output.split("\n");

        // 提取数据库信息
        List<String> databases = new ArrayList<>();
        for (String line : lines) {
            if (line.startsWith("  - ")) {
                databases.add(line.substring(4)); //包含数据库名称和时间信息
            }
        }

        return databases;
    }

    // 解析数据库信息行，返回名称和额外信息
    public static String[] splitDatabaseInfoLine(String line) {
    // 去掉前缀 "  - "，如果有
    if (line.startsWith(" - ")) {
        line = line.substring(4);
    }

    int idx = line.indexOf(" (");
    if (idx != -1) {
        String name = line.substring(0, idx).trim();
        String info = line.substring(idx).trim();
        return new String[]{name, info};
    } else {
        // 格式不符合，返回整个字符串和空字符串
        return new String[]{line.trim(), ""};
    }
}

    // 获取当前数据库名称
    public static String getCurrentDatabase() {
        Session session = Session.getCurrentSession();
        if (session == null) {
            return "[未登录]";
        }

        String dbName = session.getCurrentDatabaseName();
        String dbOwner = session.getCurrentUser();

        if (dbName == null || dbOwner == null) {
            return "[未选择]";
        }

        return dbOwner + "." + dbName;
    }

    // 获取指定数据库中的表名
    public static List<String> getTables(String fullDbName) {
        try {
            System.out.println("[UICommandProcessor.getTables] 尝试获取数据库 " + fullDbName + " 的表列表");
            String[] parts = fullDbName.split("\\.");
            if (parts.length != 2) {
                System.err.println("[UICommandProcessor.getTables] 数据库名格式错误: " + fullDbName + "，应为 owner.dbname 格式");
                return new ArrayList<>();
            }

            String ownerName = parts[0];
            String dbName = parts[1];

            Session currentSession = Session.getCurrentSession();
            if (currentSession == null) {
                System.err.println("[UICommandProcessor.getTables] 无法获取当前会话");
                return new ArrayList<>();
            }

            // 检查系统表是否已初始化
            if (!systemDBEngine.checkSystemTablesInitialized()) {
                System.err.println("[WARN] 系统表未初始化，正在初始化...");
                systemDBEngine.initSystemTables();
            }

            // 直接使用DatabaseManager检查数据库是否存在
            System.out.println("[UICommandProcessor.getTables] 直接验证数据库 " + ownerName + "." + dbName + " 是否存在");
            boolean exists = storage.manager.DatabaseManager.databaseExists(ownerName, dbName);
            if (!exists) {
                System.err.println("[UICommandProcessor.getTables] 数据库 " + ownerName + "." + dbName + " 不存在");
                return new ArrayList<>();
            }

            // 检查是否有权限访问该数据库
            System.out.println("[UICommandProcessor.getTables] 检查对数据库 " + ownerName + "." + dbName + " 的访问权限");
            boolean hasAccess = currentSession.checkDatabaseAccess(ownerName, dbName);
            if (!hasAccess) {
                System.err.println("[UICommandProcessor.getTables] 无权访问数据库: " + ownerName + "." + dbName);
                return new ArrayList<>();
            }

            // 保存当前数据库上下文
            String origDbOwner = currentSession.getCurrentDatabaseOwnerName();
            String origDbName = currentSession.getCurrentDatabaseName();

            List<String> tables = new ArrayList<>();

            try {
                // 首先尝试使用DatabaseManager获取表
                try {
                    System.out.println("[UICommandProcessor.getTables] 使用DatabaseManager.getTablesAsString获取表");
                    String tablesOutput = DatabaseManager.getTablesAsString(ownerName, dbName);
                    if (tablesOutput != null && !tablesOutput.isEmpty()) {
                        String[] lines = tablesOutput.split("\\n");
                        for (String line : lines) {
                            line = line.trim();
                            if (line.startsWith("- ")) {
                                String tableName = line.substring(2).trim();
                                if (!tableName.isEmpty()) {
                                    tables.add(tableName);
                                }
                            }
                        }
                        System.out.println("[UICommandProcessor.getTables] 通过DatabaseManager获得 " + tables.size() + " 个表");
                    }
                } catch (Exception e) {
                    System.err.println("[UICommandProcessor.getTables] 通过DatabaseManager获取表失败: " + e.getMessage());
                }

                // 如果上面的方法没有获取到表，尝试使用直接访问系统数据库的方式
                if (tables.isEmpty()) {
                    try {
                        // 直接从系统数据库获取表信息，而不是通过SQL查询
                        System.out.println("[UICommandProcessor.getTables] 尝试直接从系统数据库获取表信息");
                        tables = systemDBEngine.getTablesForDatabase(ownerName, dbName);
                        System.out.println("[UICommandProcessor.getTables] 从系统数据库直接获得 " + tables.size() + " 个表");
                    } catch (Exception e) {
                        System.err.println("[UICommandProcessor.getTables] 从系统数据库获取表失败: " + e.getMessage());
                        e.printStackTrace();
                    }
                }

                // 如果系统表查询结果为空，尝试使用存储表信息获取
                if (tables.isEmpty()) {
                    try {
                        // 获取数据库元数据
                        System.out.println("[UICommandProcessor.getTables] 尝试从元数据获取表信息");
                        java.util.Map<String, Object> dbInfo = systemDBEngine.getDatabaseInfo(ownerName, dbName);
                        if (dbInfo != null && dbInfo.containsKey("tables")) {
                            @SuppressWarnings("unchecked")
                            List<String> dbTables = (List<String>) dbInfo.get("tables");
                            if (dbTables != null) {
                                tables.addAll(dbTables);
                            }
                        }
                        System.out.println("[UICommandProcessor.getTables] 从元数据获得 " + (tables.size()) + " 个表");
                    } catch (Exception ex) {
                        System.err.println("[UICommandProcessor.getTables] 从元数据获取表信息失败: " + ex.getMessage());
                        ex.printStackTrace();
                    }
                }

                // 记录获取到的表信息
                System.out.println("[UICommandProcessor.getTables] 为数据库 " + ownerName + "." + dbName + " 获取到 " + tables.size() + " 个表");
            } finally {
                // 无需恢复原始上下文，因为我们没有修改会话状态
            }

            return tables;
        } catch (Exception e) {
            System.err.println("[UICommandProcessor.getTables] 查询表信息失败: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static boolean useDatabase(String fullDbName) {
        try {
            System.out.println("[UICommandProcessor.useDatabase] 尝试切换到数据库: " + fullDbName);

            String[] parts = fullDbName.split("\\.");
            if (parts.length != 2) {
                System.err.println("[UICommandProcessor.useDatabase] 数据库名格式错误: " + fullDbName + "，应为 owner.dbname 格式");
                return false;
            }

            String ownerName = parts[0];
            String dbName = parts[1];

            Session currentSession = Session.getCurrentSession();
            if (currentSession == null) {
                System.err.println("[UICommandProcessor.useDatabase] 无法获取当前会话");
                return false;
            }

            // 使用DatabaseManager直接验证数据库是否存在，而不是通过SQL查询
            System.out.println("[UICommandProcessor.useDatabase] 直接验证数据库: " + ownerName + "." + dbName);
            boolean exists = storage.manager.DatabaseManager.databaseExists(ownerName, dbName);
            if (!exists) {
                System.err.println("[UICommandProcessor.useDatabase] 数据库不存在: " + ownerName + "." + dbName);
                return false;
            }

            // 检查是否有权限访问该数据库
            System.out.println("[UICommandProcessor.useDatabase] 检查访问权限");
            boolean hasAccess = currentSession.checkDatabaseAccess(ownerName, dbName);
            if (!hasAccess) {
                System.err.println("[UICommandProcessor.useDatabase] 无权访问数据库: " + ownerName + "." + dbName);
                return false;
            }

            // 设置当前数据库
            // 注意：Session.setCurrentDatabase的参数顺序是：ownerName, databaseName
            System.out.println("[UICommandProcessor.useDatabase] 设置当前数据库为: " + ownerName + "." + dbName);
            boolean success = currentSession.setCurrentDatabase(ownerName, dbName);

            if (success) {
                System.out.println("[UICommandProcessor.useDatabase] 数据库切换成功");
                // 如果切换成功且MainFrame实例存在，刷新UI
                if (ui.MainFrame.instance != null) {
                    SwingUtilities.invokeLater(() -> {
                        ui.MainFrame.instance.refreshDatabaseList();
                        ui.MainFrame.instance.updateStatusBar();
                    });
                }
            } else {
                System.err.println("[UICommandProcessor.useDatabase] 数据库切换失败，原因未知");
            }

            return success;
        } catch (Exception e) {
            System.err.println("[UICommandProcessor.useDatabase] 切换数据库出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static int dropDatabase(String fullDbName) {
        try {
            String[] parts = fullDbName.split("\\.");
            if (parts.length != 2) {
                return -1;
            }

            Session currentSession = Session.getCurrentSession();
            if (currentSession == null) {
                return -1;
            }

            // 检查权限 - 只有所有者或管理员可以删除数据库
            if (!parts[0].equals(currentSession.getUsername()) &&
                currentSession.getUserLevel() != UserManager.ADMIN_LEVEL) {
                return -1;
            }

            // 执行删除
            return currentSession.executeUpdate(
                "DROP DATABASE " + parts[0] + "." + parts[1]);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public static List<String[]> getTableInfo(String fullDbName, String tableName) {
        try {
            String[] parts = fullDbName.split("\\.");
            if (parts.length != 2) {
                return new ArrayList<>();
            }

            Session currentSession = Session.getCurrentSession();
            if (currentSession == null) {
                return new ArrayList<>();
            }

            // 查询表结构信息
            List<ArrayList<String>> results = currentSession.executeQuery(
                "SELECT column_name, data_type, is_nullable, column_default, is_primary " +
                "FROM system_columns WHERE db_owner='" + parts[0] + "' AND db_name='" + parts[1] +
                "' AND table_name='" + tableName + "' ORDER BY ordinal_position");

            List<String[]> tableInfo = new ArrayList<>();
            for (ArrayList<String> row : results) {
                tableInfo.add(row.toArray(new String[0]));
            }
            return tableInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    public static boolean connect(String url, String username, String password) {
        return true;
    }

    /**
     * 解析查询结果字符串为表格数据
     * @param resultString 查询结果字符串
     * @return 表格数据列表，第一行为表头
     */
    private static ArrayList<ArrayList<String>> lastQueryResults = null;

    public static ArrayList<ArrayList<String>> parseQueryResults(String resultString) {
        ArrayList<ArrayList<String>> results = new ArrayList<>();

        // 按行分割结果字符串
        String[] lines = resultString.split("\n");
        if (lines.length == 0) {
            return results;
        }

        // 解析表头
        String[] headers = lines[0].split("\t");
        ArrayList<String> headerList = new ArrayList<>(Arrays.asList(headers));
        results.add(headerList);

        // 解析数据行
        for (int i = 1; i < lines.length; i++) {
            String[] cells = lines[i].split("\t");
            ArrayList<String> row = new ArrayList<>(Arrays.asList(cells));
            results.add(row);
        }

        lastQueryResults = results;
        return results;
    }

    public static ArrayList<ArrayList<String>> getLastQueryResults() {
        return lastQueryResults;
    }

    // 添加新方法用于在表结构变化后刷新UI
    private static void refreshUIAfterTableChange() {
        if (ui.MainFrame.instance != null) {
            SwingUtilities.invokeLater(() -> {
                System.out.println("[UICommandProcessor] 表结构已变更，正在刷新UI...");
                ui.MainFrame.instance.refreshDatabaseList();
                ui.MainFrame.instance.dbTreePanel.refreshTree();
                ui.MainFrame.instance.updateStatusBar();
            });
        }
    }

    // 添加新方法用于在数据库变化后刷新UI
    private static void refreshUIAfterDatabaseChange() {
        if (ui.MainFrame.instance != null) {
            SwingUtilities.invokeLater(() -> {
                System.out.println("[UICommandProcessor] 当前数据库已变更，正在刷新UI...");
                ui.MainFrame.instance.refreshDatabaseList();
                ui.MainFrame.instance.updateStatusBar();
            });
        }
    }
}
